//
//  YDOAuthViewController.swift
//  YDWeibo01
//
//  Created by suibian on 16/8/10.
//  Copyright © 2016年 iitcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


class YDOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
//       判断url是否为nil
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)")else{
        return
        
        }
        //            设置代理 (代理方法里有可以实现的方法)
        webView.delegate = self
//        实例化request
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setUpNav()
    }
    
//    设置监听
    @objc private func cancelAction(){
    
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    @objc private func antoFillAction(){
    
    print("自动填充")
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPasswd)'"
//        js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
//    设置视图
    private func setupUI(){
    
    view.backgroundColor = UIColor.whiteColor()
        
    }
    
//    设置导航栏
    private func setUpNav(){
    navigationItem.title = "微博登录"
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "antoFillAction")
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelAction")
    
    }
    
//    懒加载控件
    private var webView:UIWebView = UIWebView()
    

}

extension YDOAuthViewController:UIWebViewDelegate{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        通过这个方法可以得到url的字符串
        let urlString = request.URL?.absoluteString
//        判断urlString是否为nil 如果不为nil 在判断它的前缀是否为我们设置的回调页
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_uri){
//            请求参数
            if let query = request.URL?.query{
//            获取code 截取字符串
            let code = query.substringFromIndex("code=".endIndex)
                
              print(code)
          YDUserAccountViewModel.sharedTools.getUseCount(code, finish: { (issuccess) -> () in
            return
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                //           发送通知切换跟控制器
                NSNotificationCenter.defaultCenter().postNotificationName(WEBSWITCHROOTVCNOTIFACATION, object: "oauth")
            })
            
          })
                return false
                
            }

        }
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
//        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
//        SVProgressHUD.dismiss()
    }

    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        
    }

}
//请求数据 //    抽取方法到ViewModel


















